import { reactive } from 'vue';
import { showModal } from '@/common/hooks/useShow.js';
import { checkDataState } from '@/subpages/common/api/merchant/list.js';
export default function() {
	const data = reactive({
		isPopup: false,
		checkTimer: 0,
		checkTimeout: 1000 * 5,
		updateTimer: 0,
		updateTimeout: 1000 * 120,
		checkUids: []
	});
	// 更改按钮状态
	const changeBtnsStatus = (o, list) => {
		if (o.uid) data.checkUids.push(o.uid);
		list.forEach(item => {
			if (item.mid == o.item.mid) item.contact_status = o.type || o.type == 0 ? o.type : 1;
		})
	}
	// 监听客户大厅/我的客户按钮状态
	const checkContinue = (list, type) => {
		data.checkTimer && clearInterval(data.checkTimer);
		data.checkTimer = setInterval(async () => {
			const changeList = list.filter(item => item.contact_status == 1 && item.is_online == 1);
			// console.log('changeListchangeList',changeList)
			if (changeList.length > 0) {
				const uids = ['my'].indexOf(type) > -1 ? data.checkUids : changeList.map(item => {
					return item.id
				});
				const res = await checkDataState({ uid: uids.join(',') });
				let resObj = {};
				res.data.forEach(item => {
					resObj[item.mid] = { mid: item.mid, contact_status: item.contact_status }
				})
				list.forEach((item, index) => {
					if (resObj[item.mid] && item.mid == resObj[item.mid].mid && resObj[item.mid].contact_status != 1) item.contact_status = resObj[item.mid].contact_status;
				})
			}
		}, data.checkTimeout)
	}
	// 检测是否需要刷新
	const checkRefresh = (fn) => {
		data.updateTimer && clearInterval(data.updateTimer);
		data.updateTimer = setInterval(() => {
			if (data.isPopup) return false;
			data.isPopup = true;
			showModal({
				content: `您已在本页面停留${data.updateTimeout/(1000*60)}分钟，建议刷新页面查看最新客户数据`,
				showCancel: false,
				confirmText: '刷新',
				confirm() {
					if (fn) fn();
					data.isPopup = false;
				}
			})
		}, data.updateTimeout)
	}
	// 禁用提示
	const checkForbid = (res) => {
		let msg = '';
		switch (res.prompt) {
			case 1:
				msg = `您的商户基本信息审核中，暂时不可使用CRM管理。详询QQ：${res.qq}`
				break;
			case 2:
				msg = `您的商户基本信息审核失败，可前往电脑端（商户设置-基本信息）查看失败原因并修改`
				break;
			case 3:
				msg = `文档CRM客户管理系统已升级，您需要前往电脑端（商户设置-基本信息）完善信息后方可继续使用。进QQ群了解更多：${res.qq}`
				break;
			default:
				return;
		}
		showModal({
			content: `${msg}`,
			showCancel: false,
			confirmText: '首页',
			confirm() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		})
		clearTime();
	}
	// 清除定时器
	const clearTime = () => {
		data.checkTimer && clearInterval(data.checkTimer);
		data.updateTimer && clearInterval(data.updateTimer);
	}
	return {
		changeBtnsStatus,
		checkContinue,
		checkRefresh,
		checkForbid,
		clearTime
	}
}
